package com.softlab.retailwholesalesystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.softlab.retailwholesalesystem.entity.AuthorityEntity;
import com.softlab.retailwholesalesystem.entity.MenuEntity;
import com.softlab.retailwholesalesystem.mapper.AuthorityMapper;
import com.softlab.retailwholesalesystem.mapper.MenuMapper;
import com.softlab.retailwholesalesystem.service.IAuthorityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthorityServiceImpl extends ServiceImpl<AuthorityMapper, AuthorityEntity> implements IAuthorityService {

    @Autowired
    AuthorityMapper mapper;

    @Autowired
    MenuMapper menuMapper;

    @Override
    public List<AuthorityEntity> getList(AuthorityEntity authority) {
        QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("u.is_delete",0);
        if (authority.getAuthorityId()!=null) wrapper.eq("u.authority_id",authority.getAuthorityId());
        if (authority.getRoleId()!=null) wrapper.eq("u.role_id",authority.getRoleId());
        if (authority.getMenuId()!=null) wrapper.eq("u.menu_id",authority.getMenuId());
        return mapper.getList(wrapper);
    }

    @Override
    public List<MenuEntity> getRoleAuthorities(int roleId) {
        QueryWrapper<AuthorityEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("is_delete",0).eq("role_id",roleId);
        List<AuthorityEntity> list = mapper.selectList(wrapper);
        List<Integer> roleIds = new ArrayList<>();
        for (AuthorityEntity entity : list) {
            roleIds.add(entity.getMenuId());
        }
        QueryWrapper<MenuEntity> menuWrapper = new QueryWrapper<>();
        menuWrapper.eq("is_delete",0);
        List<MenuEntity> menuEntityList = menuMapper.getAllMenu();
        for (MenuEntity menuEntity : menuEntityList) {
            if (roleIds.contains(menuEntity.getMenuId())) {
                menuEntity.setKeepAlive(1);
            }
            if(menuEntity.getChildren()!=null){
                List<MenuEntity> children = menuEntity.getChildren();
                for (MenuEntity child : children) {
                    if (roleIds.contains(child.getMenuId())) {
                        child.setKeepAlive(1);
                    }
                }
            }
        }
        return menuEntityList;
    }
}
